﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OTS.BLL;
using OTS.Model;
using DevExpress.Web.ASPxEditors;

public partial class OLPC_MCToOrder : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl1);
            SettingRight();
            Session["dtlist"] = null;
            Session["assigneddt"] = null;
            InitUi();
            tc.ActiveTabIndex = 0;
        }
    }
    // 页面权限
    private void SettingRight()
    {
        bool[] rightlist = SysRightBLL.GetRightByType(new string[] { 
            Session["UserCode"].ToString(), 
            Session["CoCode"].ToString(), 
            "mctoorder"});
        if (!rightlist[0])
        { this.Page.Response.Write(String.Format("<script language='javascript'>window.parent.location.href='{0}';</script>", CommonModel.loginOut1)); }

        gv.Columns[0].Visible = rightlist[1];
        gvAssigned.Columns[1].Visible = rightlist[2];
        gvAssigned.Columns[2].Visible = rightlist[3];
        btnadd.Visible = rightlist[1];

        rightlist = SysRightBLL.GetRightByType(new string[] { 
            Session["UserCode"].ToString(), 
            Session["CoCode"].ToString(), 
            "mcCreditCheck"});
        hidIsEnabledCreditCheck.Value = rightlist[2] ? "1" : "0";
    }

    // 初始化绑定
    private void InitUi()
    {
        CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl1);
        InitDataBind();
        //CollectionTypeBind();
        InitAssignedDataBind();
        //ContractNoBind("");
        cbContractNo.Text = "";
    }
    // 已有数据
    private void InitDataBind()
    {
        DataTable tempdt = new DataTable();
        if (Session["dtlist"] != null)
        {
            tempdt = Session["dtlist"] as DataTable;
        }
        else
        {
            tempdt = AccountStatementItemBLL.GetList(" TransactionAmountLeft>0 and HandlingFee=0 and Accepted=0 ");
            gv.DataSource = tempdt;
            gv.DataBind();
        }
        gv.DataSource = tempdt;
        gv.DataBind();
        Session["dtlist"] = tempdt;
    }
    // 已匹配收款数据
    private void InitAssignedDataBind()
    {
        DataTable tempdt = new DataTable();
        if (Session["assigneddt"] != null)
        {
            tempdt = Session["assigneddt"] as DataTable;
        }
        else
        {
            tempdt = AccountStatementManualBLL.GetList("");
            gvAssigned.DataSource = tempdt;
            gvAssigned.DataBind();
        }
        gvAssigned.DataSource = tempdt;
        gvAssigned.DataBind();
        Session["assigneddt"] = tempdt;
    }

    protected void gv_AfterPerformCallback(object sender, 
        DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
    {
        InitDataBind();
    }

    // 匹配行事件
    protected void gv_RowCommand(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewRowCommandEventArgs e)
    {
        try
        {
            string temp = e.CommandArgs.CommandArgument.ToString();
            int Inttemp = int.Parse(temp);
            string cmd = e.CommandArgs.CommandName;
            if (cmd == "assigning")
            {
                #region
                int rowindex = e.VisibleIndex;

                string id=e.KeyValue.ToString();
                AccountStatementItemModel model = new AccountStatementItemModel();
                model = AccountStatementItemBLL.GetModel(id);

                if (model != null && model.BankReference!=null && model.BankReference.Trim().Length>0)
                {
                    txtBankReference.Text = model.BankReference;
                    txtOrderingPartyName.Text = model.OrderingPartyName;
                    txtTransactionAmount.Text = model.TransactionAmount;
                    txtTransactionAmountAssigned.Text = model.AppliedAmount.ToString();
                    txtTransactionAmountLeft.Value = model.TransactionAmountLeft;
                    txtType.Text = model.AccountsReceivable;
                    txtCustomerCode2.Text = model.CustomerCode;
                    txtCustomerName.Text = model.CustomerName;
                    ContractNoBind("");
                    string contractno = cbContractNo.Text.Trim();
                    contractno = contractno.Contains("请选择") ? "" : contractno;
                    string strWhere = contractno.Length > 0 ? string.Format(" and O.ContractNoMain='{0}'", contractno) : "";
                    OrderNoBind(strWhere);

                    tc.ActiveTabIndex = 2;
                    lblAccountStatementItemCode.Text = id;
                }
                EditOrView(false);
                btnadd.Visible = true;

                #endregion
            }
        }
        catch (Exception ex)
        {
            Log.WritLog("gv_RowCommand:", ex.ToString());
        }
    }

    // Collection Type
    private void CollectionTypeBind()
    {
        DataTable dt = AccountStatementManualBLL.GetCollectionType();
        cbCollectionType.DataSource = dt;
        cbCollectionType.ValueField = "CollectionType";
        cbCollectionType.TextField = "CollectionType";
        cbCollectionType.DataBind();
        cbCollectionType.Items.Insert(0, new ListEditItem("请选择 (Please Select)", "-1"));
    }
    // 获取合同号
    private void ContractNoBind(string strWhere)
    {
        string tempcontractno = cbContractNo.Text.Trim();
        string strcondiction = string.Format(" and Ltrim(Rtrim(CustomerNo))=Ltrim(Rtrim('{0}')) {1}", 
            txtCustomerCode2.Text, strWhere);
        DataTable dt = AccountStatementManualBLL.GetContractNo(strcondiction);
        cbContractNo.DataSource = dt;
        cbContractNo.ValueField = "ContractNoMain";
        cbContractNo.TextField = "ContractNoMain";
        cbContractNo.DataBind();
        cbContractNo.Items.Insert(0, new ListEditItem("请选择 (Please Select)", "-1"));
        if (tempcontractno != null && tempcontractno.Length > 0)
        {
            for (int i = 0; i < cbContractNo.Items.Count; i++)
            {
                if (cbContractNo.Items[i].Text.ToString().Contains(tempcontractno))
                {
                    cbContractNo.SelectedIndex = i;
                    cbContractNo.Text = cbContractNo.Items[i].Text;
                    break;
                }
            }
        }
        if (cbContractNo.SelectedIndex < 1 && cbContractNo.Items.Count > 1)
        {
            cbContractNo.SelectedIndex = 1;
        }
    }
    // Order
    private void OrderNoBind(string str)
    {
        string temporderno = cbSalesOrder.Text.Trim();
        string strcondiction = string.Format(" and Ltrim(Rtrim(CustomerNo))=Ltrim(Rtrim('{0}')) {1} ",
            txtCustomerCode2.Text, str);
        DataTable dt = AccountStatementManualBLL.GetSalesOrderByContractNo(strcondiction);
        cbSalesOrder.DataSource = dt;
        cbSalesOrder.ValueField = "OrderNo";
        cbSalesOrder.TextField = "OrderNo";
        cbSalesOrder.DataBind();
        cbSalesOrder.Items.Insert(0, new ListEditItem("请选择 (Please Select)", "-1"));
        if (temporderno != null && temporderno.Length > 0)
        {
            for (int i = 0; i < cbSalesOrder.Items.Count; i++)
            {
                if (cbSalesOrder.Items[i].Text.ToString().Contains(temporderno))
                {
                    cbSalesOrder.SelectedIndex = i;
                    break;
                }
            }
        }
        if (cbSalesOrder.SelectedIndex < 1 && cbSalesOrder.Items.Count > 1)
        { cbSalesOrder.SelectedIndex = 1; }
        bool flag1 = cbContractNo.SelectedIndex < 1;
        bool flag2 = cbSalesOrder.SelectedIndex < 1;
        string orderno = flag2 ? "" : cbSalesOrder.Text.Trim();
        string cantractno = flag1 ? "" : cbContractNo.Text.Trim();

        if (!flag1 && !flag2)
        {
            DataTable tempdt = AccountStatementManualBLL.GetContractOrderInfo(cantractno, orderno);
            if (tempdt != null && tempdt.Rows.Count > 0)
            {
                DataRow row = tempdt.Rows[0];
                txtSalesOrderAmountVAT.Value = row["OrderValue"].ToString();
                txtSalesman.Text = row["SalesName"].ToString();
                txtCustomerCode.Text = row["CustomerNo"].ToString();
                txtCustomer.Text = row["CustomerName"].ToString();
                txtCAppliedAmount.Text = row["CAppliedAmount"].ToString();
                txtOAppliedAmount.Text = flag2 ? "0" : (row["OAppliedAmount"].ToString());
                txtCEName.Text = row["CEName"].ToString();
            }
        }
        //}
        //else
        //    CommonMethod.regAlertMessage(upd, "请输入合同号！", this);
    }

    protected void cbContractNo_TextChanged(object sender, EventArgs e)
    {
        string contractno = cbContractNo.Text.Trim();
        cbContractNo.SelectedIndex = 0;
        cbSalesOrder.Text = "";
        cbSalesOrder.Items.Clear();
        Clear();
        contractno = contractno.Contains("请选择") ? "" : contractno;
        bool cexists = false;
        if (contractno.Length > 0)
        {
            for (int i = 1; i < cbContractNo.Items.Count; i++)
            {
                if (cbContractNo.Items[i].Text.Trim() == contractno)
                {
                    cbContractNo.SelectedIndex = i;
                    cexists = true;
                    break;
                }
            }
        }
        if (cexists)
        {
            contractno = cbContractNo.Text.Trim();
        }
        else
        {
            ContractNoBind(string.Format(" and O.ContractNoMain like '%{0}%'", contractno));
        }
        if (cbContractNo.Items.Count > 1)
        {
            contractno = cbContractNo.Text.Trim();
            OrderNoBind(string.Format(" and O.ContractNoMain like '%{0}%'", contractno));
        }
    }

    protected void cbSalesOrder_TextChanged(object sender, EventArgs e)
    {
        string orderno = cbSalesOrder.Text.Trim();
        Clear();
        orderno = orderno.Contains("请选择") ? "" : orderno;
        string strWhere = string.Format(" and O.OrderNo like '%{0}%'", orderno);
        cbContractNo.Text = "";
        ContractNoBind(strWhere);
        if (cbContractNo.Items.Count > 1)
        {
            string contractno = cbContractNo.Text.Trim();
            contractno = contractno.Contains("请选择") ? "" : contractno;
            strWhere += string.Format(" and O.ContractNoMain='{0}'", contractno);
            OrderNoBind(strWhere);
        }
    }

    private void Clear()
    {
        cbContractNo.Text = "";
        //cbContractNo.Items.Clear();
        cbSalesOrder.Text = "";
        //cbSalesOrder.Items.Clear();
        txtSalesOrderAmountVAT.Value = "0";
        txtCAppliedAmount.Text = "0";
        txtOAppliedAmount.Text = "0";
        txtSalesman.Text = "";
        txtCASO.Text = "0";
        txtApplyAmount.Text = "0";
        txtCustomerCode.Text = "";
        txtCustomer.Text = "";
        cbCollectionType.SelectedIndex = 0;
        //cbCollectionType.Text = "";
        txtUnallocatedBalance.Text = "";
        //txtType.Text = "";
        chbCreditCheck.Checked = false;
        chbiScalabookedcheck.Checked = false;
    }

    protected void gvAssigned_AfterPerformCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
    {
        InitAssignedDataBind();
    }
    protected void gvAssigned_RowCommand(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewRowCommandEventArgs e)
    {
        try
        {
            string temp = e.CommandArgs.CommandArgument.ToString();
                string id = e.KeyValue.ToString();
            string cmd = e.CommandArgs.CommandName;
            if (cmd == "edit")
            {
                #region 编辑

                Clear();
                cbContractNo.SelectedIndex = 0;
                cbSalesOrder.SelectedIndex = 0;
                AssignedOrViewBind(1, id, temp);
                EditOrView(false);
                
                #endregion
            }
            else if (cmd == "delete")
            {
                #region 删除

                bool resultFlag = AccountStatementManualBLL.Delete(long.Parse(id));
                string message = "删除失败！";
                if (resultFlag)
                {
                    Session["assigneddt"] = null;
                    Session["dtlist"] = null;
                    InitAssignedDataBind();
                    InitDataBind();
                    message = "删除成功!";
                }
                CommonMethod.regAlertMessage(upd, message, this);

                #endregion
            }
            else if (cmd == "view")
            {
                #region 查看

                Clear();
                AssignedOrViewBind(0, id, temp);
                //ccorder.Enabled = false;
                EditOrView(true);
                
                #endregion
            }
        }
        catch (Exception ex)
        {
            Log.WritLog("gvAssigned_RowCommand:", ex.ToString());
        }
    }
    // 已匹配收款编辑、查看绑定
    private void AssignedOrViewBind(int actionflag, string id, string AccountStatementItemCode)
    {
        AccountStatementManualModel model = new AccountStatementManualModel();
        model = AccountStatementManualBLL.GetModel(long.Parse(id));
        if (model != null && model.ContractNo != null && model.ContractNo.Trim().Length > 0)
        {
            if (!string.IsNullOrEmpty(model.ContractNo))
            {
                #region 合同号
                for (int i = 0; i < cbContractNo.Items.Count; i++)
                {
                    if (cbContractNo.Items[i].Text == model.ContractNo)
                    {
                        cbContractNo.SelectedIndex = i;
                        break;
                    }
                }
                #endregion
            }
            cbContractNo.Text = model.ContractNo;
            if (!string.IsNullOrEmpty(model.SalesOrderNo))
            {
                #region 订单号
                for (int i = 0; i < cbSalesOrder.Items.Count; i++)
                {
                    if (cbSalesOrder.Items[i].Text == model.SalesOrderNo)
                    {
                        cbSalesOrder.SelectedIndex = i;
                        break;
                    }
                }
                #endregion
            }
            cbSalesOrder.Text = model.SalesOrderNo;
            txtSalesOrderAmountVAT.Value = model.SalesOrderAmountVAT;
            txtSalesman.Text = model.Salesman;
            txtCASO.Text = model.CollectionAgainstSalesman;
            txtApplyAmount.Text = model.ApplyAmount.ToString();
            txtCustomerCode.Text = model.CustomerCode;
            txtCustomer.Text = model.Customer;
            txtCEName.Text = model.CEName;
            if (!string.IsNullOrEmpty(model.CollectionType))
            {
                #region 收款类型
                for (int i = 0; i < cbCollectionType.Items.Count; i++)
                {
                    if (cbCollectionType.Items[i].Text == model.CollectionType)
                    {
                        cbCollectionType.SelectedIndex = i;
                        break;
                    }
                }
                #endregion
            }
            cbCollectionType.Text = model.CollectionType;
            txtUnallocatedBalance.Text = model.UnallocatedBalance;
            txtType.Text = model.Type;
            chbCreditCheck.Checked = model.CreditCheck == 1;
            chbiScalabookedcheck.Checked = model.iScalaBookedCheck == 1;

            DataTable tempdt = AccountStatementManualBLL.GetContractOrderInfo(model.ContractNo, model.SalesOrderNo);
            if (tempdt != null && tempdt.Rows.Count > 0)
            {
                DataRow row = tempdt.Rows[0];
                txtCAppliedAmount.Text = row["CAppliedAmount"] == null ? "0" : row["CAppliedAmount"].ToString();
                txtOAppliedAmount.Text = row["OAppliedAmount"] == null ? "0" : row["OAppliedAmount"].ToString();
            }

            lblAccountStatementItemCode.Text = AccountStatementItemCode;
            BankBind(AccountStatementItemCode);

            tc.ActiveTabIndex = 2;
            hidid.Value = id;
            btnadd.Visible = false;
            btnedit.Visible = actionflag == 1 ? true : false;
        }
    }
    private void EditOrView(bool flag)
    {
        cbContractNo.ReadOnly = flag;
        cbSalesOrder.ReadOnly = flag;
        txtApplyAmount.ReadOnly = flag;
        txtApplyAmount.Enabled = !false;
        cbCollectionType.ReadOnly = flag;
    }

    private void BankBind(string AccountStatementItemCode)
    {
        AccountStatementItemModel model2 = new AccountStatementItemModel();
        model2 = AccountStatementItemBLL.GetModel(AccountStatementItemCode);
        if (model2 != null && model2.BankReference != null && model2.BankReference.Trim().Length > 0)
        {
            txtBankReference.Text = model2.BankReference;
            txtOrderingPartyName.Text = model2.OrderingPartyName;
            txtTransactionAmount.Text = model2.TransactionAmount;
            txtTransactionAmountAssigned.Text = model2.AppliedAmount.ToString();
            txtTransactionAmountLeft.Value = model2.TransactionAmountLeft;
            txtType.Text = model2.AccountsReceivable;
            txtCustomerCode2.Text = model2.CustomerCode;
            txtCustomerName.Text = model2.CustomerName;
        }
    }

    private bool Check()
    {
        if (txtBankReference.Text.Length == 0)
        {
            CommonMethod.regAlertMessage(upd, "BankReference can't be null ", this);
            return false;
        }
        else if (cbContractNo == null || cbContractNo.SelectedIndex == 0)
        {
            CommonMethod.regAlertMessage(upd, "ContractNO can't be null ", this);
            return false;
        }
        else if (cbSalesOrder == null || cbSalesOrder.SelectedIndex == 0)
        {
            CommonMethod.regAlertMessage(upd, "SalesOrder can't be null ", this);
            return false;
        }
        else if (string.IsNullOrEmpty(txtApplyAmount.Text.Trim()))
        {
            CommonMethod.regAlertMessage(upd, "Apply Amount can't be null ", this);
            return false;
        }
        else if (!CommonMethod.CheckNUM(txtApplyAmount.Text.Trim()))
        {
            CommonMethod.regAlertMessage(upd, "Apply Amount must be number ", this);
            return false;
        }
        else if (txtApplyAmount.Text.Trim() == "0")
        {
            CommonMethod.regAlertMessage(upd, "Apply Amount can't be 0 ", this);
            return false;
        }
        else if (!CommonMethod.CheckNUM(txtSalesOrderAmountVAT.Value.Trim()))
        {
            CommonMethod.regAlertMessage(upd, "Sales Order Amount(VAT) must be number ", this);
            return false;
        }
        else if (txtSalesOrderAmountVAT.Value.Trim() == "0")
        {
            CommonMethod.regAlertMessage(upd, "Sales Order Amount(VAT) can't be 0 ", this);
            return false;
        }// 申请匹配金额
        float applyamount = float.Parse(txtApplyAmount.Text);
        // 可匹配金额
        float transactionamountleft = float.Parse(txtTransactionAmountLeft.Value);
        // 订单金额
        float salesorderamountVAT = float.Parse(txtSalesOrderAmountVAT.Value);
        if (applyamount <= transactionamountleft)
        {
            if (applyamount > salesorderamountVAT)
            {
                CommonMethod.regAlertMessage(upd, "申请金额不得大于订单金额！", this);
                return false;
            }
        }
        else
        {
            CommonMethod.regAlertMessage(upd, "申请金额不得大于可匹配金额！",this);
            return false;
        }

        return true;
    }
    private AccountStatementManualModel SetModel(AccountStatementManualModel model)
    {
        model.AccountStatementItemCode = lblAccountStatementItemCode.Text;
        model.ContractNo = cbContractNo.Text.Trim();
        model.SalesOrderNo = cbSalesOrder.Text.Trim();
        model.SalesOrderAmountVAT = txtSalesOrderAmountVAT.Value;
        model.Salesman = txtSalesman.Text;
        model.CollectionAgainstSalesman = txtCASO.Text;
        model.ApplyAmount = float.Parse(txtApplyAmount.Text);
        model.CustomerCode = txtCustomerCode.Text.Trim();
        model.Customer = txtCustomer.Text.Trim();
        model.CEName = txtCEName.Text.Trim();
        model.CollectionType = cbCollectionType.Text.Trim();
        model.UnallocatedBalance = txtUnallocatedBalance.Text.Trim();
        model.Type = txtType.Text.Trim();
        model.CreditCheck = chbCreditCheck.Checked ? 1 : 0;
        model.iScalaBookedCheck = chbiScalabookedcheck.Checked ? 1 : 0;
        model.ADDDATE = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        model.ADDAUTHOR = Session["UserCode"] == null ? "10000" : Session["UserCode"].ToString();
        model.UPDATEDATE = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        model.UPDATEAUTHOR = Session["UserCode"] == null ? "10000" : Session["UserCode"].ToString();
        model.StateValue = "0";
        model.StateText = "收款匹配";

        return model;
    }
    protected void btnadd_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl1);
        bool flag = Check();
        if (flag)
        {
            AccountStatementManualModel model = new AccountStatementManualModel();
            model = SetModel(model);
            string message = "添加失败！";
            bool resultFlag = AccountStatementManualBLL.Add(model);

            if (resultFlag)
            {
                Session["assigneddt"] = null;
                Session["dtlist"] = null;
                InitDataBind();
                InitAssignedDataBind();
                message = "添加成功!";
                Clear();
                BankBind(lblAccountStatementItemCode.Text);
            }
            CommonMethod.regAlertMessage(upd, message, this);
        }
    }
    protected void btnedit_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl1);
        bool flag = Check();
        if (flag)
        {
            AccountStatementManualModel model = new AccountStatementManualModel();
            model = SetModel(model);
            model.AccountStatementManualID = long.Parse(hidid.Value);
            string message = "保存失败！";
            bool resultFlag = AccountStatementManualBLL.Update(model);

            if (resultFlag)
            {
                Session["assigneddt"] = null;
                Session["dtlist"] = null;
                InitDataBind();
                InitAssignedDataBind();
                message = "保存成功!";
                tc.ActiveTabIndex = 1;
                Clear();
                btnedit.Visible = false;
                btnadd.Visible = gv.Columns[0].Visible;
                BankBind(lblAccountStatementItemCode.Text);
            }
            CommonMethod.regAlertMessage(upd, message, this);
        }
    }

    // 数据导出
    protected void btnMathingExport_Click(object sender, EventArgs e)
    {
        InitDataBind();

        gv.Columns[0].Visible = false;
        gridready.WriteXlsToResponse();
        gv.Columns[0].Visible = true;
    }
    protected void btnMathedExport_Click(object sender, EventArgs e)
    {
        InitAssignedDataBind();

        gvAssigned.Columns[0].Visible = false;
        gvAssigned.Columns[1].Visible = false;
        gvAssigned.Columns[2].Visible = false;
        gvAssigned.Columns[3].Visible = false;
        gridreadied.WriteXlsToResponse();
        gvAssigned.Columns[0].Visible = true;
        gvAssigned.Columns[1].Visible = true;
        gvAssigned.Columns[2].Visible = true;
        gvAssigned.Columns[3].Visible = true;
    }

    #region Checked

    public bool IsVisibale(string statevalue)
    {
        return "0" == statevalue;
    }
    public bool IsEnabledCreditCheck()
    {
        return "1" == hidIsEnabledCreditCheck.Value;
    }
    public bool CreditChecked(string CreditCheck)
    {
        return "1" == CreditCheck;
    }
    protected void chk_CreditCheck(object sender, EventArgs e)
    {
        CheckBox chk = sender as CheckBox;
        string strid = chk.ToolTip;
        string f = chk.Checked ? "1" : "0";
        bool flag = AccountStatementManualBLL.Update(strid, f);
        if (flag)
        {
            Session["assigneddt"] = null;
            InitAssignedDataBind();
        }
        else
        {
            chk.Checked = !chk.Checked;
            CommonMethod.regAlertMessage(upd, "设置失败！", this);
        }
    }

    #endregion
}